import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { oauthAPI } from "@/api";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import { useTranslation } from "react-i18next";
import type { AxiosError } from "axios";
import type { ErrorResponse } from "@/types/response";
import type { OAuthProviderInfo } from "@/api/oauth";
import { useEffect } from "react";
import type { Provider } from "@/types/oauth";

interface UseAccountBindingReturn {
  // 数据
  providers: OAuthProviderInfo[];
  isLoadingProviders: boolean;
  providersError: unknown;

  // 操作
  handleLinkAccount: (provider: Provider) => void;
  handleUnlinkAccount: (provider: Provider) => void;
  handleSetPrimaryEmail: (provider: Provider) => void;

  // 状态
  isLinking: boolean;
  isUnlinking: boolean;
  isSettingPrimaryEmail: boolean;

  // 刷新
  refetchProviders: () => void;
}

/**
 * 账户绑定相关的 hooks
 */
export function useAccountBinding(): UseAccountBindingReturn {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();

  // 获取 OAuth 提供商列表 - 添加性能优化
  const {
    data: providersResponse,
    isLoading: isLoadingProviders,
    error: providersError,
    refetch: refetchProviders,
  } = useQuery({
    queryKey: ["oauth-providers"],
    queryFn: oauthAPI.getProviders,
    staleTime: 5 * 60 * 1000, // 5分钟，减少不必要的重新获取
    gcTime: 10 * 60 * 1000, // 10分钟垃圾回收时间
  });

  const providers = providersResponse?.data ?? [];

  // 绑定 OAuth 账户 - 使用 oauthAPI.login 启动绑定流程
  const linkMutation = useMutation({
    mutationFn: oauthAPI.login,
    onSuccess: (response) => {
      if (response.code === 200) {
        // 重定向到 OAuth 提供商进行绑定
        // 后端应该能够检测到用户已登录，自动进行绑定而不是登录
        window.location.href = response.data.auth_url;
      } else {
        toast.error(t("Failed to start OAuth binding"), {
          description:
            response.message ||
            t("An error occurred while starting OAuth binding."),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      const errorResult = errorHandler.handleApiError(error);
      toast.error(t("Failed to start OAuth binding"), {
        description: errorResult.message,
        duration: 5000,
      });
    },
  });

  // 解绑 OAuth 账户 mutation - 添加乐观更新
  const unlinkMutation = useMutation({
    mutationFn: oauthAPI.unlink,
    onMutate: async ({ provider }) => {
      // 乐观更新：立即更新UI，假设解绑成功
      await queryClient.cancelQueries({ queryKey: ["oauth-providers"] });

      const previousProviders = queryClient.getQueryData(["oauth-providers"]);

      // 乐观更新提供商列表
      queryClient.setQueryData(["oauth-providers"], (old: unknown) => {
        const typedOld = old as { data?: OAuthProviderInfo[] };
        if (!typedOld?.data) return old;
        return {
          ...typedOld,
          data: typedOld.data.map((p: OAuthProviderInfo) =>
            p.provider === provider ? { ...p, linked: false } : p
          ),
        };
      });

      return { previousProviders };
    },
    onSuccess: (response) => {
      if (response.code === 200) {
        toast.success(t("Account unlinked successfully"), {
          description: t("Your account has been successfully unlinked."),
          duration: 3000,
        });
        // 确保数据是最新的
        queryClient.invalidateQueries({ queryKey: ["oauth-providers"] });
      } else {
        toast.error(t("Failed to unlink account"), {
          description:
            response.message || t("An error occurred while unlinking account."),
          duration: 5000,
        });
      }
    },
    onError: (
      error: AxiosError<ErrorResponse, unknown>,
      _variables,
      context
    ) => {
      // 回滚乐观更新
      if (context?.previousProviders) {
        queryClient.setQueryData(
          ["oauth-providers"],
          context.previousProviders
        );
      }

      const errorResult = errorHandler.handleApiError(error);
      toast.error(t("Failed to unlink account"), {
        description: errorResult.message,
        duration: 5000,
      });
    },
  });

  // 设置主邮箱 mutation
  const setPrimaryEmailMutation = useMutation({
    mutationFn: oauthAPI.setPrimaryEmail,
    onSuccess: (response) => {
      if (response.code === 200) {
        toast.success(t("Primary email updated successfully"), {
          description: t("Your primary email has been successfully updated."),
          duration: 3000,
        });
        queryClient.invalidateQueries({ queryKey: ["oauth-providers"] });
        queryClient.invalidateQueries({ queryKey: ["user"] });
      } else {
        toast.error(t("Failed to set primary email"), {
          description:
            response.message || t("An error occurred while setting primary email."),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      const errorResult = errorHandler.handleApiError(error);
      toast.error(t("Failed to set primary email"), {
        description: errorResult.message,
        duration: 5000,
      });
    },
  });

  // 处理绑定账户
  const handleLinkAccount = (provider: Provider) => {
    if (linkMutation.isPending || unlinkMutation.isPending || setPrimaryEmailMutation.isPending) {
      return; // 防止重复点击
    }
    linkMutation.mutate(provider);
  };

  // 处理解绑账户
  const handleUnlinkAccount = (provider: Provider) => {
    if (linkMutation.isPending || unlinkMutation.isPending || setPrimaryEmailMutation.isPending) {
      return; // 防止重复点击
    }
    unlinkMutation.mutate({ provider });
  };

  // 处理设置主邮箱
  const handleSetPrimaryEmail = (provider: Provider) => {
    if (linkMutation.isPending || unlinkMutation.isPending || setPrimaryEmailMutation.isPending) {
      return; // 防止重复点击
    }
    setPrimaryEmailMutation.mutate({ provider });
  };

  // 检查URL参数，判断是否是从OAuth绑定回调返回的
  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const oauthSuccess = urlParams.get("oauth_success");
    const oauthError = urlParams.get("oauth_error");
    const oauthAlreadyLinked = urlParams.get("oauth_already_linked");

    if (oauthSuccess === "true") {
      toast.success(t("Account linked successfully"), {
        description: t("Your account has been successfully linked."),
        duration: 3000,
      });
      // 刷新提供商列表
      refetchProviders();
      // 清除URL参数
      const newUrl = window.location.pathname;
      window.history.replaceState({}, "", newUrl);
    } else if (oauthError) {
      toast.error(t("Failed to link account"), {
        description:
          oauthError || t("An error occurred while linking account."),
        duration: 5000,
      });
      // 清除URL参数
      const newUrl = window.location.pathname;
      window.history.replaceState({}, "", newUrl);
    } else if (oauthAlreadyLinked === "true") {
      toast.error(t("Failed to link account"), {
        description: t("This OAuth account is already linked to another user."),
        duration: 5000,
      });
      // 清除URL参数
      const newUrl = window.location.pathname;
      window.history.replaceState({}, "", newUrl);
    }
  }, [t, refetchProviders]);

  return {
    // 数据
    providers,
    isLoadingProviders,
    providersError,

    // 操作
    handleLinkAccount,
    handleUnlinkAccount,
    handleSetPrimaryEmail,

    // 状态
    isLinking: linkMutation.isPending,
    isUnlinking: unlinkMutation.isPending,
    isSettingPrimaryEmail: setPrimaryEmailMutation.isPending,

    // 刷新
    refetchProviders,
  };
}
